import 'package:base_moudle/index.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../../../models/data_model/HyWorkModel.dart';
import '../../../../new_paltform/define/hy_header.dart';
import '../../db/work_app_model.dart';
import '../hy_work_home_logic.dart';
import '../my_work/hy_me_work_logic.dart';

class HYAddSearchPage extends StatefulWidget {
  static Future? push({int code = 1}) {
    return Get.to(() =>
        HYAddSearchPage(
          code: code,
        ));
  }

  HYAddSearchPage({this.code = 1});

  int code;

  @override
  State<StatefulWidget> createState() {
    return _HYAddSearchPageState();
  }
}

class _HYAddSearchPageState extends State<HYAddSearchPage> {
  HyHomeGetxController get controller {
    if (widget.code == 2) {
      HyMeWorkHomeLogic _controller = Get.find();
      return _controller;
    } else {
      HyWorkHomeLogic _controller = Get.find();
      return _controller;
    }
  }

  List<Rx<ItemModel>> list = <Rx<ItemModel>>[];

  RxString searchStr = ''.obs;

  @override
  Widget build(BuildContext context) {
    return PageViewBase(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: searchContainer(),
        shadowColor: Colors.transparent,
      ),
      body:
      // Obx(() {
      //   return
      ListView.builder(
        itemCount: list.isNotEmpty ? list.length : 1,
        itemBuilder: (BuildContext context, int index) {
          if (list.isNotEmpty) {
            return allApplyWidget(model: list[index], index: index);
          } else {
            return Container(
              margin: const EdgeInsets.only(top: 40),
              child: Column(
                children: <Widget>[
                  Stack(
                    alignment: Alignment.bottomCenter,
                    children: <Widget>[
                      Image.asset(
                        'assets/images/empty_data.png',
                        width: Get.width - 80,
                        fit: BoxFit.cover,
                      ),
                      Container(
                        margin: const EdgeInsets.only(bottom: 40),
                        child: Text(
                          '暂无数据',
                          style: TextStyle(color: zs_black_999, fontSize: 16),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            );
          }
        },
      ),
      // }),
    );
  }

  Widget searchContainer() {
    return HYContainer(
      borderRadius: const BorderRadius.all(Radius.circular(22)),
      backgroundColor: zs_color_background,
      child: HYCupertinoTextField(
        prefixMode: OverlayVisibilityMode.always,
        prefix: Container(
          padding: const EdgeInsets.only(
            left: 12,
            top: 10,
            bottom: 10,
            right: 8,
          ),
          child: Image.asset(
            'assets/images/homeIcons/home_search.png',
            width: 24,
            height: 24,
          ),
        ),
        hintText: '搜索应用',
        hintTextColor: zs_black_999,
        textColor: zs_black_333,
        textFontSize: 14,
        textInputAction: TextInputAction.search,
        onChanged: (String value) {
          searchStr.value = value;
          containsStr(value);
        },
        onSubmitted: (String value) {
          searchStr.value = value;
          containsStr(value);
        },
        suffixMode: OverlayVisibilityMode.always,
        suffix: HYContainer(
          padding: const EdgeInsets.only(
            left: 16,
            top: 12,
            bottom: 12,
            right: 16,
          ),
          child: Text(
            '取消',
            style: TextStyle(fontSize: 16, color: zs_mainColor),
          ),
          onTap: () {
            Get.back();
          },
        ),
      ),
    );
  }

  void containsStr(String str) {
    if (list.isNotEmpty) {
      list.clear();
    }

    if (str != '') {
      list = List<ItemModel>.from(controller.allList
          .where((ItemModel element) => element.title.contains(str))
          .toList())
          .map((e) => e.obs)
          .toList();
    }
    setState(() {});
  }

  Widget allApplyWidget({required Rx<ItemModel> model, int? index}) {
    return Container(
      padding: EdgeInsets.only(
          left: 15, top: index == 0 ? 30 : 15, bottom: 15, right: 15),
      child: Row(
        children: <Widget>[
          if (model.value.iconName.contains('http'))
            CachedNetworkImage(
              imageUrl: model.value.iconName,
              width: 50,
              height: 50,
              fit: BoxFit.cover,
              errorWidget: (BuildContext c, String s, i) {
                return Container(
                  // margin: EdgeInsets.all(15),
                  width: 50, height: 50,
                  decoration: BoxDecoration(
                      color: zs_color_f2,
                      borderRadius: BorderRadius.circular(8)),
                );
              },
            )
          else
            Image.asset(
              model.value.iconName,
              width: 50,
              height: 50,
            ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.only(left: 16, right: 16),
              child: RichText(
                text: TextSpan(children: splitStr(title: model.value.title)),
              ),
            ),
          ),
          HYContainer(
            width: 56,
            height: 30,
            alignment: Alignment.center,
            borderRadius: const BorderRadius.all(Radius.circular(6)),
            border: Border.all(
              color: model.value.isDisplay == true
                  ? Colors.transparent
                  : ColorHex('#187AFF'),
            ),
            child: Text(
              model.value.isDisplay == true ? '已添加' : '添加',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: model.value.isDisplay == true
                    ? zs_color_ccc
                    : ColorHex('#187AFF'),
              ),
            ),
            onTap: () async {
              if (model.value.isDisplay == false) {
                int rank = controller.itemList.length + 1;
                await HyWorkAppModel.saveAddLikeModel(
                    model: model.value, rank: rank, code: widget.code)
                    .whenComplete(() => EasyLoading.showToast('添加成功'));
                model.value.isDisplay = true;
                controller.onItemList();
              }
              setState(() {});
            },
          ),
        ],
      ),
    );
  }

  List<InlineSpan> splitStr({required String title}) {
    final String s1 = title;
    final List<String> textList = s1.split('');
    final List<InlineSpan> list = <InlineSpan>[];
    for (final String str in textList) {
      list.add(
        TextSpan(
          text: str,
          style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              color: searchStr.contains(str) ? zs_mainColor : zs_black_333),
        ),
      );
    }
    return list;
  }

  void refreshInterface() {
    Timer.periodic(const Duration(milliseconds: 200), (timer) {
      controller.onItemList();
    });
  }
}
